package com.wholesale;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ViewFlipper;

import com.wholesale.utils.Constants;

public class CartActivity extends Activity{
	private ViewFlipper viewFlipper ;
	DataReceiver dataReceiver;// BroadcastReceiver对象
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		viewFlipper = (ViewFlipper)findViewById(R.id.viewFlipper);
		Cart1Layout cartLayout = new Cart1Layout(this, viewFlipper);
		viewFlipper.addView(cartLayout);
		
	}
	private class DataReceiver extends BroadcastReceiver {// 继承自BroadcastReceiver的子类
		@Override
		public void onReceive(Context context, Intent intent) {
			int cmd = intent.getIntExtra("cmd", -1);// 获取Extra信息
			if(cmd == Constants.CMD_LOGOUT_SERVICE){
				viewFlipper.removeAllViews();
				CartLayout cartLayout = new CartLayout(CartActivity.this, viewFlipper);
				viewFlipper.addView(cartLayout);
			}else{
				((Cart1Layout)viewFlipper.getChildAt(0)).updateShopCar();
			}
		}
	}
	
	@Override
	protected void onStart() {// 重写onStart方法
		Intent myIntent = new Intent();// 创建Intent对象
		myIntent.setAction("com.wholesale.utils.UpdateUIService");
		myIntent.putExtra("cmd", Constants.CMD_OPENCAR_SERVICE);
		myIntent.putExtra("from", "com.wholesale.CartActivity");
		sendBroadcast(myIntent);
		dataReceiver = new DataReceiver();
		IntentFilter filter = new IntentFilter();// 创建IntentFilter对象
		filter.addAction("com.wholesale.CartActivity");
		registerReceiver(dataReceiver, filter);// 注册Broadcast Receiver
		super.onStart();
	}

	@Override
	protected void onStop() {// 重写onStop方法
		unregisterReceiver(dataReceiver);// 取消注册Broadcast Receiver
		super.onStop();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(viewFlipper.getChildCount()>1){
				viewFlipper.showPrevious();
				viewFlipper.removeViewAt(viewFlipper.getChildCount()-1);
				return true ;
			}else{
				return false ;
			}
		}else{
			return super.onKeyDown(keyCode, event);
		}
	}
}

